/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

/**
 * 判断是否是外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path)
  return isExternal
}
/**
 * 将br替换成\n,然后将html标签去除
 * @param {*} text
 * @returns
 */
export function removeHtmlTags(text: string) {
  return text.replace(/<br ?\/?>/g, '\n').replace(/<[^>]*>/g, '')
}
/**
 * 复制函数
 * @param text 要复制文本
 * @param removeHTMLTags 是否去除html标签
 */
export let copyText:any = (text: string, removeHTMLTags = false) => {
  if ('clipboard' in navigator && typeof navigator.clipboard.writeText === 'function') {
    copyText = clipboardCopy
  } else {
    copyText = execCommandCopy
  }
  copyText(text, removeHTMLTags)
}
/**
 * 新版复制api
 * @param {*} text
 * @returns
 */
function clipboardCopy(text: string, removeHTMLTags = false) {
  const cleanText = removeHTMLTags ? removeHtmlTags(text) : text
  navigator.clipboard.writeText(cleanText)
}
function execCommandCopy(text: string, removeHTMLTags = false) {
  console.log(text);
  const textarea = document.createElement('textarea')
  textarea.value = removeHTMLTags ? text.replace(/<[^>]*>/g, '') : text
  textarea.style.position = 'fixed'
  textarea.style.top = '0'
  textarea.style.left = '0'
  textarea.style.opacity = '0'
  document.body.appendChild(textarea)
  textarea.focus()
  textarea.select()
  document.execCommand('copy')
  document.body.removeChild(textarea)
}
